<?php

namespace common\drivers\queue;
/**
 * RedisQueue.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/12/31- 上午11:54
 */

use common\drivers\interfaces\JobInterface;
use Yii;
class RedisQueue
{
    /**
     * redis服务
     * @var [type]
     */
    protected $redis;

    /**
     * 队列名称
     * @var [type]
     */
    protected $queue_name;


    /**
     * 初始化
     * RedisQueue constructor.
     * @param string $queue_name
     */
    function __construct($queue_name = '')
    {
        $this->redis = Yii::$app->redis;
        $this->queue_name = $queue_name;
    }


    /**
     * 入队
     * @param JobInterface $job
     * @return mixed
     */
    public function push(JobInterface $job)
    {
        return $this->redis->lpush($this->getRedisKey(), serialize($job));
    }

    /**
     * 出队列
     * @return
     */
    public function pull()
    {
        $job_seria = $this->redis->rpop($this->getRedisKey());
        $job       = unserialize($job_seria);

        if (false === $job ||
            ! $job instanceof JobInterface
        ) {
            return false;
        }

        return $job;
    }

    /**
     * 获取队列任务总数
     * @return [type] [description]
     */
    public function count()
    {
        return $this->redis->llen($this->getRedisKey());
    }

    /**
     * 返回redis存储的key名
     * @return [type] [description]
     */
    protected function getRedisKey()
    {
        $name = ! empty($this->queue_name) ? $this->queue_name : $this->getRedisDefaultKeyName();

        return 'queues:' . $name;
    }

    /**
     * 获取默认的key名
     * @return [type] [description]
     */
    protected function getRedisDefaultKeyName()
    {
        return 'default';
    }
}